package com.example.scoredemo.widgets

import android.content.Context
import android.os.SystemClock
import android.util.AttributeSet
import android.widget.Chronometer
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.LifecycleOwner


/**
 *@time : 2021/3/23
 *@author :muzi102
 *@Description
 */
public class MyChronometer(context: Context?, attrs: AttributeSet?) : Chronometer(context, attrs),
    LifecycleEventObserver {

    companion object {
        var elasedTime: Long = 0
    }


    override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {

        when (event) {
            //暂停
            Lifecycle.Event.ON_PAUSE -> {
                elasedTime = SystemClock.elapsedRealtime() - base
                stop()
            }

            //运行
            Lifecycle.Event.ON_RESUME -> {
                base = SystemClock.elapsedRealtime() - elasedTime
                start()
            }
        }
    }

}



